Hi hamzashah5,
Refer below example and modify your code.
Database
I am making use of Northwind database Employee table. For more details refer below article.
Download Northwind
Controller
public class HomeController : Controller
{
NorthwindEntities db = new NorthwindEntities();
// GET: Home
public ActionResult Index()
{
ViewBag.Countries = db.Employees
.Select(m => new SelectListItem()
{
Text = m.Country,
Value = m.Country
}).Distinct().ToList();
return View();
}
public JsonResult LoadCitiesByCountry(string country)
{
var cities = db.Employees.Where(x => x.Country == country)
.Select(m => new SelectListItem()
{
Text = m.City,
Value = m.City
}).Distinct().ToList();
return Json(cities, JsonRequestBehavior.AllowGet);
}
public JsonResult LoadEmployees(string country, string city)
{
var data = db.Employees.Where(m => m.Country == country && m.City == city)
.Select(x => new
{
x.EmployeeID,
x.FirstName,
x.LastName,
x.City,
x.Country
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
View
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#ddlCountries").change(function () {
var country = $(this).val();
var txt = $("#dd_Company option:selected").text();
$.getJSON("../Home/LoadCitiesByCountry", { country: country },
function (classesData) {
var select = $("#ddlCities");
select.empty();
select.append($('<option/>', {
value: 0,
text: "Select a City"
}));
$.each(classesData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
$("#ddlCities").change(function () {
var country = $("#ddlCountries").val();
var city = $(this).val();
$.getJSON("../Home/LoadEmployees", { country: country, city: city },
function (response) {
var table = $('#tblCustomers');
$(table).find("tr:gt(0)").remove();
var rows = "";
for (var i = 0; i < response.length; i++) {
var id = response[i].EmployeeID;
var name = response[i].FirstName + ' ' + response[i].LastName;
var city = response[i].City;
var country = response[i].Country;
rows += "<tr><td>" + id +
"</td><td>" + name +
"</td><td>" + city +
"</td><td>" + country +
"</td></tr>";
}
table.append(rows);
});
});
});
</script>
</head>
<body>
Country:@Html.DropDownList("ddlCountries", (IEnumerable<SelectListItem>)ViewBag.Countries, "Select Country", new { id = "ddlCountries" })
<br />
City:@Html.DropDownList("ddlCities", new List<SelectListItem>(), new { id = "ddlCities" })
<hr />
<table id="tblCustomers">
<tr>
<th>EmployeeID</th>
<th>Name</th>
<th>City</th>
<th>Country</th>
</tr>
</table>
</body>
</html>
Screenshot